import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getProducts, getHotProducts, getNewProducts, getRecommendedProducts } from '@/api/product'

export const useProductStore = defineStore('product', () => {
  const productList = ref<any[]>([])
  const total = ref(0)
  const loading = ref(false)

  // 获取商品列表
  const fetchProducts = async (params?: any) => {
    try {
      loading.value = true
      const response = await getProducts(params)
      if (response.data && response.data.content) {
        productList.value = response.data.content
        total.value = response.data.totalElements
      }
      return response.data
    } catch (error: any) {
      console.error('获取商品列表失败:', error)
      return { success: false, message: error.response?.data?.message || '获取商品列表失败' }
    } finally {
      loading.value = false
    }
  }

  // 获取热门商品
  const getHotProductsList = async () => {
    try {
      const response = await getHotProducts()
      console.log('热门商品API响应:', response)
      if (response.data && response.data.success && response.data.products) {
        return response.data.products
      }
      return []
    } catch (error: any) {
      console.error('获取热门商品失败:', error)
      return []
    }
  }

  // 获取最新商品
  const getNewProductsList = async () => {
    try {
      const response = await getNewProducts()
      console.log('最新商品API响应:', response)
      if (response.data && response.data.success && response.data.products) {
        return response.data.products
      }
      return []
    } catch (error: any) {
      console.error('获取最新商品失败:', error)
      return []
    }
  }

  // 获取推荐商品
  const getRecommendedProductsList = async () => {
    try {
      const response = await getRecommendedProducts()
      console.log('推荐商品API响应:', response)
      if (response.data && response.data.success && response.data.products) {
        return response.data.products
      }
      return []
    } catch (error: any) {
      console.error('获取推荐商品失败:', error)
      return []
    }
  }

  return {
    productList,
    total,
    loading,
    fetchProducts,
    getHotProductsList,
    getNewProductsList,
    getRecommendedProductsList
  }
}) 